package com.citydo.webrtcspringboot.transfer.mqtt;

import com.citydo.webrtcspringboot.entity.SteamRotation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//MQTT 客户端类，用于连接到 MQTT 代理并订阅主题
@Slf4j
@Component
public class TBMqttClient {
    @Value("rotationSpeed")
    public static String SteamRotationTopic = "rotationSpeed";
    public static IMqttAsyncClient IMqttAsyncClient;
    private final MqttConnectOptions options;
    private final MqttMessageHandler mqttMessageHandler;

//    public TBMqttClient() throws MqttException {
//        mqttClient.connect(options);
//    }
    public TBMqttClient(IMqttAsyncClient iMqttAsyncClient, MqttMessageHandler mqttMessageHandler, MqttConnectOptions options){
        IMqttAsyncClient = iMqttAsyncClient;
        this.mqttMessageHandler = mqttMessageHandler;
        this.options = options;
        connectAndSubscribe();
    }

    public void connectAndSubscribe() {
        try {
            IMqttAsyncClient.connect(options, 1, new IMqttActionListener() {
                @SneakyThrows
                @Override
                public void onSuccess(IMqttToken iMqttToken) {
//                    IMqttAsyncClient.subscribe(SteamRotationTopic,1, mqttMessageHandler);
                }

                @Override
                public void onFailure(IMqttToken iMqttToken, Throwable throwable) {

                }
            });
        } catch (Exception e) {
            log.warn("连接主机发生异常");
            e.printStackTrace();
        }
    }

}
